package com.zahb.qadx.ui.activity.topic;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.githang.statusbar.StatusBarCompat;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.model.HistoricalPerformanceBean;
import com.zahb.qadx.model.ResultsBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

//考试成绩页
public class ResultsPageActivity extends BaseActivity {
    @BindView(R.id.score)
    TextView score;
    @BindView(R.id.correct)
    TextView correct;
    @BindView(R.id.annotations)
    TextView annotations;
    @BindView(R.id.with_time)
    TextView withTime;
    @BindView(R.id.total_number_f)
    TextView totalNumberF;
    @BindView(R.id.correct_number)
    TextView correctNumber;
    @BindView(R.id.error_number)
    TextView errorNumber;
    @BindView(R.id.paper_based)
    LinearLayout paperBased;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.position)
    LinearLayout position;
    @BindView(R.id.error_parsing)
    Button errorParsing;
    @BindView(R.id.all_error_parsing)
    Button allErrorParsing;
    @BindView(R.id.scroll_view)
    NestedScrollView scrollView;
    private ResultsBean mResultsBean;
    BaseQuickAdapter<ResultsBean.StatisticsListBean, BaseViewHolder> mAdapter;
    private String examUserResultId, sourceId;
    private HistoricalPerformanceBean mHistoricalPerformanceBean;
    private OptionsPickerView<String> mDifficultyPickerView; //条件选择器
    private List<String> stringList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUnbinder = ButterKnife.bind(this);
        navigationInitialization();//状态栏
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        recyclerView.setLayoutManager(mLayoutManager);

        examUserResultId = getIntent().getStringExtra("examUserResultId");
        sourceId = getIntent().getStringExtra("sourceId");
        if (sourceId != null) {
            historicalPerformance();
            mTopBarEndText.setText("历史成绩");
            mTopBarEndText.setTextColor(getResources().getColor(R.color.white));
            mTopBarEndContainer.setVisibility(View.VISIBLE);
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mTopBarEndContainer.getLayoutParams();
            lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            mTopBarEndContainer.setLayoutParams(lp);


            mTopBarEndText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mDifficultyPickerView = new OptionsPickerBuilder(ResultsPageActivity.this, new OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3, View v) {
                            //返回的分别是三个级别的选中位置
                            examUserResultId=mHistoricalPerformanceBean.getResultInfoList().get(options1).getUserExamResultId()+"";
                            results(mHistoricalPerformanceBean.getResultInfoList().get(options1).getUserExamResultId() + "");



                        }
                    }).setTitleText("历史成绩").build();
                    mDifficultyPickerView.setPicker(stringList);
                    mDifficultyPickerView.show();
                }
            });
        } else {
            results(examUserResultId);
        }
    }
    private void historicalPerformance() {
        addDisposable(RetrofitService.getNetService()
                .getHistoricalPerformance(sourceId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        mHistoricalPerformanceBean = response.getData();
                        for (int i = 0; i < mHistoricalPerformanceBean.getResultInfoList().size(); i++) {
                            stringList.add(mHistoricalPerformanceBean.getResultInfoList().get(i).getOpenTime() + "");
                        }
                        examUserResultId=mHistoricalPerformanceBean.getResultInfoList().get(0).getUserExamResultId()+"";
                        results(mHistoricalPerformanceBean.getResultInfoList().get(0).getUserExamResultId() + "");

                    } else {

                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    private void results(String examUserResultId) {


        addDisposable(RetrofitService.getNetService()
                .getPerformanceInformation(examUserResultId, "")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {


                        mResultsBean = response.getData();
                        if (mResultsBean != null) {
                            score.setText(mResultsBean.getScore() + "分");
                            Double cCom = ((double) mResultsBean.getRightQuestionCount() / mResultsBean.getTotalQuestion()) * 100;

                            correct.setText("正确率" + doubleToString(cCom) + "%");
                            if (mResultsBean.getAnswerTime() < 60) {
                                withTime.setText(mResultsBean.getAnswerTime() + "秒");
                            } else {
                                withTime.setText((mResultsBean.getAnswerTime() / 60) + "分钟");
                            }
                            totalNumberF.setText(mResultsBean.getUserAnswerCount() + "道");
                            correctNumber.setText(mResultsBean.getRightQuestionCount() + "道");
                            errorNumber.setText(mResultsBean.getWrongQuestionCount() + "道");
                            if (mResultsBean.getWrongQuestionCount()==0){
                                errorParsing.setVisibility(View.INVISIBLE);
                            }


                        }
                        mAdapter = new BaseQuickAdapter<ResultsBean.StatisticsListBean, BaseViewHolder>(R.layout.test_question_parsing) {
                            @Override
                            protected void convert(@NotNull BaseViewHolder baseViewHolder, ResultsBean.StatisticsListBean statisticsListBean) {
                                TextView textView = baseViewHolder.findView(R.id.topic_type);
                                TextView total_question = baseViewHolder.findView(R.id.total_question);
                                TextView right_question_count = baseViewHolder.findView(R.id.right_question_count);
                                TextView wrong_question_count = baseViewHolder.findView(R.id.wrong_question_count);
                                TextView examination_paper_analysis = baseViewHolder.findView(R.id.examination_paper_analysis);
                                TextView error_rate = baseViewHolder.findView(R.id.error_rate);
                                TextView error_parsing = baseViewHolder.findView(R.id.error_parsing);
                                total_question.setText(statisticsListBean.getTotalQuestion() + "道");//全部
                                right_question_count.setText(statisticsListBean.getRightQuestionCount() + "道");//正确
                                wrong_question_count.setText(statisticsListBean.getWrongQuestionCount() + "道");//错误
                                Double cCom = ((double) statisticsListBean.getRightQuestionCount() / statisticsListBean.getTotalQuestion()) * 100;
                                error_rate.setText(doubleToString(cCom)  + "%");
                                if (statisticsListBean.getWrongQuestionCount() == 0) {
                                    error_parsing.setVisibility(View.GONE);
                                } else {
                                    error_parsing.setVisibility(View.VISIBLE);
                                }
                                scrollView.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        scrollView.fullScroll(NestedScrollView.FOCUS_UP);

                                    }
                                });
                                error_parsing.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Intent intent = new Intent(ResultsPageActivity.this, TestQuestionParsingActivity.class);
                                        intent.putExtra("examUserResultId", examUserResultId);
                                        intent.putExtra("type", "1");
                                        intent.putExtra("limitCheck", mResultsBean.getLimitCheck());
                                        intent.putExtra("questionType", statisticsListBean.getQuestionType() + "");
                                        startActivity(intent);
                                    }
                                });
                                examination_paper_analysis.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        Intent intent = new Intent(ResultsPageActivity.this, TestQuestionParsingActivity.class);
                                        intent.putExtra("examUserResultId", examUserResultId);
                                        intent.putExtra("type", "0");
                                        intent.putExtra("limitCheck", mResultsBean.getLimitCheck());
                                        intent.putExtra("questionType", statisticsListBean.getQuestionType() + "");
                                        startActivity(intent);
                                    }
                                });
                                switch (statisticsListBean.getQuestionType()) {
                                    case 1:
                                        textView.setText("单选题");
                                        break;
                                    case 2:
                                        textView.setText("多选题");
                                        break;
                                    case 3:
                                        textView.setText("判断题");
                                        break;
                                    case 4:
                                        textView.setText("填空题");
                                        break;
                                    case 5:
                                        textView.setText("简答题");
                                        break;
                                    case 6:
                                        textView.setText("案例题");
                                        break;
                                }

                            }
                        };
                        if (mResultsBean != null) {


                            Flowable.fromIterable(mResultsBean.getStatisticsList()).filter(it -> it.getTotalQuestion() > 0).toList().subscribe(new Consumer<List<ResultsBean.StatisticsListBean>>() {
                                @Override
                                public void accept(List<ResultsBean.StatisticsListBean> statisticsListBeans) throws Exception {
                                    mAdapter.addData(statisticsListBeans);

                                }
                            });
                            recyclerView.setAdapter(mAdapter);
                        }

                    } else {

                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));

    }
    /**
     * double转String,保留小数点后两位
     * @param num
     * @return
     */
    public static String doubleToString(double num){
        //使用0.00不足位补0，#.##仅保留有效位
        return new DecimalFormat("0.00").format(num);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_results_page;
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected int getTitleStringRes() {
        return R.string.item_results;
    }

    private void navigationInitialization() {
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.blue));//状态栏颜色
        mTopBarContainer.setBackgroundColor(getResources().getColor(R.color.blue));//头部布局颜色
        mTitle_view.setTextColor(getResources().getColor(R.color.white));//标题颜色
        Drawable drawable = getResources().getDrawable(R.mipmap.fanhui);//返回箭头
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());// 设置边界
        // param 左上右下
        mTopBarStartText.setCompoundDrawables(drawable, null, null, null);
        mTopBarStartText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @OnClick({R.id.error_parsing, R.id.all_error_parsing})
    public void onClick(View view) {
        Intent intent = new Intent(ResultsPageActivity.this, TestQuestionParsingActivity.class);
        intent.putExtra("examUserResultId", examUserResultId);
        intent.putExtra("limitCheck", mResultsBean.getLimitCheck());
        intent.putExtra("questionType", "");
        switch (view.getId()) {
            case R.id.error_parsing:
                intent.putExtra("type", "1");
                startActivity(intent);
                break;
            case R.id.all_error_parsing:
                intent.putExtra("type", "2");
                startActivity(intent);
                break;
        }
    }
}
